<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2019-03-26
 */

namespace app\admin\controller;

use think\Db;
use think\Page;
use think\Config;

class ShopFreight extends Base {

    /**
     * 构造方法
     */
    public function __construct(){
        parent::__construct();
    }

    // 运费模板列表
    public function index()
    {
        // 搜索条件
        $where = [];
        $keywords = input('keywords/s');
        $keywords = addslashes(trim($keywords));
        if (!empty($keywords)) $where['a.template_name'] = ['LIKE', "%{$keywords}%"];

        // 查询模板列表
        $count = DB::name('shop_freight_template')->alias('a')->where($where)->count();
        $Page = new Page($count, config('paginate.list_rows'));
        $template = Db::name('shop_freight_template')->field('a.*,b.express_name')->alias('a')->join('shop_express b','a.express_id=b.express_id', 'left')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('a.default asc, a.template_id desc')->select();
        foreach ($template as $key => $value) {
            $value['special_ids'] = !empty($value['special_ids']) ? ltrim($value['special_ids'], ',') : '';
            $value['special_data'] = !empty($value['special_data']) ? unserialize($value['special_data']) : [];
            $value['template_ids'] = !empty($value['template_ids']) ? ltrim($value['template_ids'], ',') : '';
            $value['template_data'] = !empty($value['template_data']) ? unserialize($value['template_data']) : [];
            $template[$key] = $value;
        }

        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('pager', $Page);
        $this->assign('template', $template);
        return $this->fetch();
    }

    // 新增运费模板
    public function add()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');

            // 运费模板数据
            $times = getTime();
            $insert = [
                'add_time' => $times,
                'update_time' => $times,
                'status' => !empty($post['status']) ? intval($post['status']) : 0,
                'default' => !empty($post['default']) ? intval($post['default']) : 0,
                'express_id' => !empty($post['express_id']) ? intval($post['express_id']) : 0,
                'template_name' => !empty($post['template_name']) ? strval($post['template_name']) : '',
                'template_ids' => '',
                'template_data' => '',
                'special_set' => 1,
                'special_ids' => '',
                'special_data' => '',
            ];

            // 运费设置处理
            if (!empty($post['template_data']['freight_fee']) && !empty($post['template_data']['freight_ids'])) {
                $freight_ids = !empty($post['template_data']['freight_ids']) ? $post['template_data']['freight_ids'] : [];
                $freight_fee = !empty($post['template_data']['freight_fee']) ? $post['template_data']['freight_fee'] : [];
                $freight_names = !empty($post['template_data']['freight_names']) ? $post['template_data']['freight_names'] : [];
                $insert['template_ids'] = ',' . implode(',', $freight_ids);
                $templateData = [];
                foreach ($freight_ids as $key => $value) {
                    $templateData[] = [
                        'freight_ids' => !empty($value) ? ',' . $value : $value,
                        'freight_fee' => !empty($freight_fee[$key]) ? floatval($freight_fee[$key]) : 0,
                        'freight_names' => !empty($freight_names[$key]) ? $freight_names[$key] : '',
                    ];
                }
                $insert['template_data'] = !empty($templateData) ? serialize($templateData) : '';
            }

            // 特俗区域设置处理
            if (!empty($post['special_set'])) {
                $postSpecialData = !empty($post['special_data_' . $post['special_set']]) ? $post['special_data_' . $post['special_set']] : '';
                if (!empty($postSpecialData)) {
                    $insert['special_set'] = intval($post['special_set']);
                    $insert['special_ids'] = !empty($postSpecialData[0]) ? strval(',' . $postSpecialData[0]) : 0;
                    $specialData = [
                        'special_ids' => !empty($postSpecialData[0]) ? strval(',' . $postSpecialData[0]) : '',
                        'special_names' => !empty($postSpecialData[1]) ? strval($postSpecialData[1]) : '',
                    ];
                    $insert['special_data'] = !empty($specialData) ? serialize($specialData) : '';
                }
            }

            $insertID = Db::name('shop_freight_template')->insertGetId($insert);
            if (!empty($insertID)) {
                $this->success('添加成功', url('ShopFreight/index'));
            } else {
                $this->error('添加失败，刷新重试');
            }
        }

        // 快递公司列表
        $where = [
            'is_choose' => 1,
        ];
        $express = Db::name('shop_express')->where($where)->order('sort_order asc, express_id asc')->select();
        $this->assign('express', $express);

        return $this->fetch();
    }

    // 编辑运费模板
    public function edit()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');

            // 运费模板数据
            $times = getTime();
            $update = [
                'template_id' => intval($post['template_id']),
                'update_time' => $times,
                'status' => !empty($post['status']) ? intval($post['status']) : 0,
                'default' => !empty($post['default']) ? intval($post['default']) : 0,
                'express_id' => !empty($post['express_id']) ? intval($post['express_id']) : 0,
                'template_name' => !empty($post['template_name']) ? strval($post['template_name']) : '',
                'template_ids' => '',
                'template_data' => '',
                'special_set' => 1,
                'special_ids' => '',
                'special_data' => '',
            ];

            // 运费设置处理
            if (!empty($post['template_data']['freight_fee']) && !empty($post['template_data']['freight_ids'])) {
                $freight_ids = !empty($post['template_data']['freight_ids']) ? $post['template_data']['freight_ids'] : [];
                $freight_fee = !empty($post['template_data']['freight_fee']) ? $post['template_data']['freight_fee'] : [];
                $freight_names = !empty($post['template_data']['freight_names']) ? $post['template_data']['freight_names'] : [];
                $templateData = [];
                foreach ($freight_ids as $key => $value) {
                    $templateData[] = [
                        'freight_ids' => !empty($value) ? ',' . ltrim($value, ',') : 0,
                        'freight_fee' => !empty($freight_fee[$key]) ? floatval($freight_fee[$key]) : 0,
                        'freight_names' => !empty($freight_names[$key]) ? $freight_names[$key] : '',
                    ];
                    $update['template_ids'] .= !empty($value) ? ltrim($value, ',') : ',0,';
                }
                $update['template_data'] = !empty($templateData) ? serialize($templateData) : '';
            }

            // 特俗区域设置处理
            if (!empty($post['special_set'])) {
                $postSpecialData = !empty($post['special_data_' . $post['special_set']]) ? $post['special_data_' . $post['special_set']] : '';
                if (!empty($postSpecialData)) {
                    $update['special_set'] = intval($post['special_set']);
                    $update['special_ids'] = !empty($postSpecialData[0]) ? strval(',' . ltrim($postSpecialData[0], ',')) : 0;
                    $specialData = [
                        'special_ids' => !empty($postSpecialData[0]) ? strval(',' . ltrim($postSpecialData[0], ',')) : '',
                        'special_names' => !empty($postSpecialData[1]) ? strval($postSpecialData[1]) : '',
                    ];
                    $update['special_data'] = !empty($specialData) ? serialize($specialData) : '';
                }
            }

            $updateID = Db::name('shop_freight_template')->where($where)->update($update);
            if (!empty($updateID)) {
                $this->success('编辑成功', url('ShopFreight/index'));
            } else {
                $this->error('编辑失败，刷新重试');
            }
        }

        // 查询运费模板
        $template_id = input('param.template_id/d', 0);
        $where = [
            'template_id' => ['EQ', intval($template_id)]
        ];
        $template = Db::name('shop_freight_template')->where($where)->find();
        $template['special_ids'] = !empty($template['special_ids']) ? ltrim($template['special_ids'], ',') : '';
        $template['special_data'] = !empty($template['special_data']) ? unserialize($template['special_data']) : [];
        $template['template_ids'] = !empty($template['template_ids']) ? ltrim($template['template_ids'], ',') : '';
        $template['template_data'] = !empty($template['template_data']) ? unserialize($template['template_data']) : [];
        if (empty($template)) $this->error('运费模板不存在');
        $this->assign('template', $template);

        // 快递公司列表
        $where = [
            'is_choose' => 1,
        ];
        $express = Db::name('shop_express')->where($where)->order('sort_order asc, express_id asc')->select();
        $this->assign('express', $express);

        return $this->fetch();
    }

    public function area_list()
    {
        $serial_id = input('param.serial_id/s', '');
        $this->assign('serial_id', $serial_id);

        $provinceList = get_province_list();
        foreach ($provinceList as $key => $value) {
            if (in_array($key, [1, 338, 10543])) {
                $provinceList[$key]['cityList'] = get_area_list($key+1);
            } else if (in_array($key, [31929])) {
                $provinceList[$key]['cityList'] = get_area_list($key);
            } else {
                $provinceList[$key]['cityList'] = get_city_list($key);
            }
        }
        $this->assign('provinceList', $provinceList);

        return $this->fetch();
    }

    public function special_area_list()
    {
        $special_id = input('param.special_id/d', 0);
        $this->assign('special_id', $special_id);

        $provinceList = get_province_list();
        foreach ($provinceList as $key => $value) {
            if (in_array($key, [1, 338, 10543])) {
                $provinceList[$key]['cityList'] = get_area_list($key+1);
            } else if (in_array($key, [31929])) {
                $provinceList[$key]['cityList'] = get_area_list($key);
            } else {
                $provinceList[$key]['cityList'] = get_city_list($key);
            }
        }
        $this->assign('provinceList', $provinceList);

        return $this->fetch();
    }

    // 运费模板设置默认
    // public function ajaxTemplateDefault()
    // {
    //     if (IS_AJAX_POST) {
    //         $value = input('post.value/d', 0);
    //         $template_id = input('post.template_id/d', 0);
    //         if (!empty($value) && !empty($template_id)) {
    //             $times = getTime();
    //             $where = [
    //                 'template_id' => ['EQ', intval($template_id)]
    //             ];
    //             $update = [
    //                 'default' => intval($value),
    //                 'update_time' => $times,
    //             ];
    //             $updateID = Db::name('shop_freight_template')->where($where)->update($update);
    //             if (!empty($updateID)) {
    //                 if (1 === intval($value)) {
    //                     $where = [
    //                         'template_id' => ['NEQ', intval($template_id)]
    //                     ];
    //                     $update = [
    //                         'default' => 2,
    //                         'update_time' => $times,
    //                     ];
    //                     Db::name('shop_freight_template')->where($where)->update($update);
    //                 }
    //                 $this->success('操作成功', url('ShopFreight/index'));
    //             }
    //         }
    //         $this->error('操作失败，刷新重试');
    //     }
    // }

    // 运费模板状态设置
    // public function ajaxTemplateStatus()
    // {
    //     if (IS_AJAX_POST) {
    //         $value = input('post.value/d', 0);
    //         $template_id = input('post.template_id/d', 0);
    //         if (!empty($value) && !empty($template_id)) {
    //             $where = [
    //                 'template_id' => ['EQ', intval($template_id)]
    //             ];
    //             $update = [
    //                 'status' => intval($value),
    //                 'update_time' => getTime(),
    //             ];
    //             $updateID = Db::name('shop_freight_template')->where($where)->update($update);
    //             if (!empty($updateID)) $this->success('操作成功', url('ShopFreight/index'));
    //         }
    //         $this->error('操作失败，刷新重试');
    //     }
    // }

    // 运费模板删除
    public function ajaxTemplateDel()
    {
        if (IS_AJAX_POST) {
            $template_id = input('post.template_id/d', 0);
            if (!empty($template_id)) {
                $where = [
                    'template_id' => ['EQ', intval($template_id)]
                ];
                $deleteID = Db::name('shop_freight_template')->where($where)->delete(true);
                if (!empty($deleteID)) $this->success('删除成功', url('ShopFreight/index'));
            }
            $this->error('删除失败，刷新重试');
        }
    }
}